package com.ywk.base.concurrency.threadPool.myThreadPool;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicLong;

/**《线程池管理器》
 * 线程实现类（简易实现，自行优化.提供思路）
 *
 * @Author yjian
 * @Date 14:49 2017/10/14
 **/
@SuppressWarnings("ALL")
public class MyThreadPoolImpl implements IMyThreadPool {
    //默认开启线程个数
    static int WORKER_NUMBER = 5;
    //完成任务线程数 可见性
    static volatile int sumCount = 0;
    //任务队列 list非线程安全，可以优化为 BlockingQueue
    static BlockingQueue<Runnable> taskQueue;
    //线程工作组
    WorkerThread[] workThreads;
    //原子性
    static AtomicLong threadNum = new AtomicLong();

    static MyThreadPoolImpl threadPool;
    // 对象锁
    final static Object lock=new Object();

    //构造方法
    public MyThreadPoolImpl() {
        this(WORKER_NUMBER);
    }

    //《工作线程》
    public MyThreadPoolImpl(int workerNum) {
        this.WORKER_NUMBER = workerNum;
        //开辟工作线程空间
        workThreads = new WorkerThread[WORKER_NUMBER];
        //开始创建工作线程
        for (int i = 0; i < WORKER_NUMBER; i++) {
            workThreads[i] = new WorkerThread();
            Thread thread = workThreads[i];
            thread.setName("ThreadPool-worker" + threadNum.incrementAndGet());
            System.out.println("初始化线程数" + (i + 1) + "---------当前线程名称:" + thread.getName());
            thread.start();
        }
    }

    @Override
    public String toString() {
        return "工作线程数量为" + WORKER_NUMBER
                + "已完成的任务数" + sumCount +
                "等待任务数量" + taskQueue.size();
    }

    //获取线程池
    public static IMyThreadPool getThreadPool(int workerNum, int taskNum) {
        taskQueue=new ArrayBlockingQueue(taskNum);
        //容错性，如果小于等于0就默认线程数
        if (workerNum <= 0) {
            workerNum = WORKER_NUMBER;
        }
        if (threadPool == null) {
            threadPool = new MyThreadPoolImpl(workerNum);
        }
        return threadPool;
    }

    //《任务队列》
    @Override
    public void execute(Runnable task) {
        synchronized (lock) {
            taskQueue.add(task);
            lock.notifyAll();
        }
    }

    @Override
    public void execute(Runnable[] tasks) {
        synchronized (lock) {
            for (Runnable task : tasks) {
                taskQueue.add(task);
            }
            lock.notifyAll();
        }
    }

    @Override
    public void execute(List<Runnable> tasks) {
        synchronized (lock) {
            for (Runnable task : tasks) {
                taskQueue.add(task);
            }
            lock.notifyAll();
        }
    }

    @Override
    public void destroy() {
        //循环是否还存在任务，如果存在等待20毫秒处理时间
        while (!taskQueue.isEmpty()) {
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果任务队列已处理完成，销毁线程，清空任务
        for (int i = 0; i < WORKER_NUMBER; i++) {
            workThreads[i].setWorkerFlag();
            workThreads[i] = null;
        }
        threadPool = null;
        taskQueue.clear();
    }

    //创建工作线程池(内部类实现)：《任务接口》
    class WorkerThread extends Thread {
        //用来标识当前线程属于活动可用状态
        public boolean isRunning = true;

        @Override
        public void run() {
            Runnable runnable = null;
            //通过死循环实现20个线程一直在运行，即有20个run()方法等待运行
            while (isRunning) {
                //非线程安全，所以采用同步锁
                synchronized (lock) {
                    while (isRunning && taskQueue.isEmpty()) {
                        try {
                            //如果任务队列为空，等待20毫秒 监听任务到达，释放锁
                            lock.wait(1);//必须设置一定的时间等待，否则不能停止工作线程
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    //任务队列不为空
                    if (!taskQueue.isEmpty()) {
                        try {
                            runnable = taskQueue.take();//获取第一个任务
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                } //此时释放锁让其他线程去抢占，不让后面的runnable.run();里的任务代码影响其他线程的运行
                if (runnable != null) {
                    runnable.run();//异步执行任务代码
                }
                sumCount++;
                runnable = null;
            }
            System.out.println("停止工作线程"+this.getName());
        }

        //销毁线程
        public void setWorkerFlag() {
            isRunning = false;
        }
    }
}
